import React from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { Menu } from 'antd';
import { NavLink, useLocation } from 'react-router-dom';
import IconFont from '@/components/IconFont';

// 获取当前链接的key
const getKeyByLink = (list, link) => {
  let key = null;
  let parentKey = null;

  list.forEach((item) => {
    if (item.link && item.link === link) {
      key = item.key;
    } else if (item.children) {
      item.children.forEach((subItem) => {
        if (subItem.link && subItem.link === link) {
          parentKey = item.key;
          key = subItem.key;
        }
      });
    }
  });

  return {
    key,
    parentKey,
  };
};
const MenuComp = ({ list }) => {
  const location = useLocation();
  const { key, parentKey } = getKeyByLink(list, location.pathname);
  const defaultSelectedKeys = [key];
  const defaultOpenKeys = parentKey ? [parentKey] : [];

  return (
    <Menu
      theme="dark"
      defaultSelectedKeys={defaultSelectedKeys}
      defaultOpenKeys={defaultOpenKeys}
      mode="inline"
    >
      {list.map((item) => {
        const children = get(item, 'children', null);

        if (children) {
          return (
            <Menu.SubMenu
              key={item.key}
              icon={<IconFont type={item.icon} />}
              title={item.name}
            >
              {children.map((sub) => (
                <Menu.Item key={sub.key}>
                  <NavLink to={sub.link ? sub.link : '#'}>{sub.name}</NavLink>
                </Menu.Item>
              ))}
            </Menu.SubMenu>
          );
        }

        return (
          <Menu.Item key={item.key} icon={<IconFont type={item.icon} />}>
            <NavLink to={item.link ? item.link : '#'}>{item.name}</NavLink>
          </Menu.Item>
        );
      })}
    </Menu>
  );
};

MenuComp.propTypes = {
  list: PropTypes.arrayOf(PropTypes.object),
};

export default MenuComp;
